package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.WebSocket.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.OrderNumberUtil;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //获取当前登录的信息
        Long userId = BaseContext.getCurrentId();

        //判断异常（地址空，购物车空）
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        List<ShoppingCart> list = shoppingCartMapper.getByUserId(userId);
        if(list == null && list.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setUserId(userId);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(OrderNumberUtil.generate(OrderNumberUtil.Strategy.TIMESTAMP_RANDOM));
        orders.setOrderTime(LocalDateTime.now());
        orders.setAddress(addressBook.getDetail());
        log.info("要插入的订单数据为：{}",orders);
        //将订单信息存入
        orderMapper.submit(orders);

        //根据订单id存入订单详细
//        List<ShoppingCart> list = shoppingCartMapper.getByUserId(userId);
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.save(orderDetail);
             log.info("已经存入订单信息，数据为：{}",orderDetail);
        }
        //情况购物车信息
        shoppingCartMapper.clean(userId);
        log.info("已经清空购物车");

        //根据订单号查询订单信息

        OrderSubmitVO orderSubmitVO = orderMapper.getByNumber(orders.getNumber());
        return orderSubmitVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */

    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {

        // 当前登录用户id

        Long userId = BaseContext.getCurrentId();

        User user = userMapper.getById(userId);


        //调用微信支付接口，生成预支付交易单

//    JSONObject jsonObject = weChatPayUtil.pay(

//        ordersPaymentDTO.getOrderNumber(), //商户订单号

//        new BigDecimal(0.01), //支付金额，单位 元

//        "苍穹外卖订单", //商品描述

//        user.getOpenid() //微信用户的openid

//    );

//

//    if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {

//  throw new OrderBusinessException("该订单已支付");

//    }


        JSONObject jsonObject = new JSONObject();

        jsonObject.put("code", "ORDERPAID");

//


        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);

        vo.setPackageStr(jsonObject.getString("package"));


        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改

        Integer OrderPaidStatus = Orders.PAID; //支付状态，已支付

        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单


        //发现没有将支付时间 check_out属性赋值，所以在这里更新

        LocalDateTime check_out_time = LocalDateTime.now();

        String orderNumber = ordersPaymentDTO.getOrderNumber();
        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, orderNumber);
        Long id = orderMapper.getByNumber(orderNumber).getId();

        //通过websocket向客户端测览器推送消息type orderId content
        Map map = new HashMap();
        map.put("type",1);//1来单提醒，2客户催单
        map.put("orderId",id);
        map.put("content", "订单号：" + orderNumber);
        String json = JSON.toJSONString(map);
        //向页面推送消息
        webSocketServer.sendToAllClient(json);

        return vo;

    }

    /**
     * 查看历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {

        //开始分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.pageQuery(ordersPageQueryDTO);

        long total = page.getTotal();
        List<OrderVO> result = page.getResult();

        for (OrderVO order : result) {
            //获取订单id
            Long orderId = order.getId();
            List<OrderDetail> orderDetail = orderDetailMapper.getById(orderId);
            log.info("orderDetail：{}，",orderDetail);
            order.setOrderDetailList(orderDetail);
        }
        log.info("total值为：{}，",total);
        log.info("订单为：{}",result);
        return new PageResult(total,result);

        //--------------------------------------------------

//        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
//
//        List<OrderVO> list = new ArrayList();
//
//        // 查询出订单明细，并封装入OrderVO进行响应
//        if (page != null && page.getTotal() > 0) {
//            for (Orders orders : page) {
//                Long orderId = orders.getId();// 订单id
//
//                // 查询订单明细
//                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderNumber(orderId);
//
//                OrderVO orderVO = new OrderVO();
//                BeanUtils.copyProperties(orders, orderVO);
//                orderVO.setOrderDetailList(orderDetails);
//                list.add(orderVO);
//            }
//        }
//        long total = page.getTotal();
//        log.info("total值为：{}，",total);
//        log.info("订单VO数据为：{}",list);
//        return new PageResult(total, list);

    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {
        Orders orders = orderMapper.getById(id);

        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        log.info("id为：{}",id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        //获取订单id
        Long orderId = orders.getId();
        log.info("orderId：{}",orderId);
        List<OrderDetail> orderDetail = orderDetailMapper.getById(orderId);
        log.info("orderDetail：{}，",orderDetail);
        orderVO.setOrderDetailList(orderDetail);
        log.info("返回的数据为：{}",orderVO);
        return orderVO;
    }

    /**
     *再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {

        Orders orders = orderMapper.getById(id);
        orders.setNumber(OrderNumberUtil.generate(OrderNumberUtil.Strategy.TIMESTAMP_RANDOM));
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        log.info("要插入的订单数据为：{}",orders);
        //将订单信息存入
        orderMapper.submit(orders);

        //根据订单id查询订单
        List<OrderDetail> orderDetail = orderDetailMapper.getById(id);
        //获取新订单id
        Long orderId = orders.getId();
        for (OrderDetail detail : orderDetail) {
            detail.setOrderId(orderId);
            orderDetailMapper.save(detail);
        }
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO,orders);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.setStatus(orders);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO getStatistics() {
        //根据当前订单状态查询数量
        Integer toBeConfirmed = orderMapper.getStatistics(Orders.TO_BE_CONFIRMED);  //待接单数量
        Integer deliveryInProgress = orderMapper.getStatistics(Orders.DELIVERY_IN_PROGRESS); //派送中数量
        Integer confirmed = orderMapper.getStatistics(Orders.CONFIRMED);  //待派送数量

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);

        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO,orders);
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.setStatus(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersRejectionDTO,orders);
        orders.setStatus(Orders.CANCELLED);
        orderMapper.setStatus(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.setStatus(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.setStatus(orders);
    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);

        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //通过websocket向客户端测览器推送消息type orderId content
        Map map = new HashMap();
        map.put("type",2);//1来单提醒，2客户催单
        map.put("orderId",id);
        map.put("content", "订单号：" + orders.getNumber());
        String json = JSON.toJSONString(map);
        //向页面推送消息
        webSocketServer.sendToAllClient(json);
    }

}
